package middleware

import (
	"encoding/json"
	"fmt"
	"gin/app/http/common"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Decrypt(c *gin.Context) {

	data, error := c.GetRawData()
	if error != nil {
		fmt.Println(error.Error())
	}
	var dataStruct struct {
		Data string `json:"data"`
	}
	err := json.Unmarshal(data, &dataStruct)
	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的数据格式"})
		c.Abort()
		return
	}
	DecryptedData, err := common.Decrypt(dataStruct.Data)

	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusBadRequest, gin.H{"error": "body解密失败"})
		c.Abort()
		return
	}
	c.Set("DecryptedData", DecryptedData)
	tokenHeader := c.GetHeader("token")
	if tokenHeader != "" {
		token, err := common.Decrypt(c.GetHeader("token"))
		if err != nil {
			fmt.Println(err.Error())
			c.JSON(http.StatusBadRequest, gin.H{"error": "token解密失败"})
			c.Abort()
			return
		}
		c.Set("token", token)
	}

	//fmt.Println(DecryptedData)
	//fmt.Println(common.DecryptAES(dataStruct.Data))
	c.Next()
}
